/* (c)2010-2013 Andrea Caltroni (andrea.caltroni@pd.infn.it), INFN (www.infn.it)
 *
 * This file is part of the IGI Survey Portlet (from here on shortened to IGISP).
 * IGISP is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) any 
 * later version.
 *
 * IGISP is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with IGISP. If not, see <http://www.gnu.org/licenses/>.
 */
package it.infn.grid.liferay.survey.modules.admin.controller;

import it.infn.grid.liferay.survey.modules.admin.web.AnswerModePropertyEditor;
import it.infn.grid.liferay.survey.modules.admin.web.AnswerValidator;
import it.infn.grid.liferay.survey.modules.admin.web.QuestionPropertyEditor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;

import org.ajm.spring.survey.modules.admin.model.Answer;
import org.ajm.spring.survey.modules.admin.model.AnswerMode;
import org.ajm.spring.survey.modules.admin.model.AnswersType;
import org.ajm.spring.survey.modules.admin.model.Question;
import org.ajm.spring.survey.modules.admin.model.Survey;
import org.ajm.spring.survey.modules.admin.service.AnswerService;
import org.ajm.spring.survey.modules.admin.service.QuestionService;
import org.ajm.spring.survey.modules.admin.service.SurveyService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

/**
 * The controller for the action of editing an existing Answer.
 * 
 * @author Andrea Caltroni, andrea.caltroni@pd.infn.it, INFN
 */
@RequestMapping(value="VIEW")
@Controller(value="editAnswerController")
public class EditAnswerController {

    // ------------------------------------------------------------------------|
    // --- CONSTANTS ----------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // --- CLASS VARIABLES ----------------------------------------------------|
    // ------------------------------------------------------------------------|
    // ------------------------------------------------------------------------|

    static Logger logger = Logger.getLogger(EditAnswerController.class);
    
    // ------------------------------------------------------------------------|
    // --- INSTANCE VARIABLES -------------------------------------------------|
    // ------------------------------------------------------------------------|

    @Autowired
    @Qualifier("answerService")
    private AnswerService answerService;
    
    @Autowired
    @Qualifier("questionService")
    private QuestionService questionService;
    
    @Autowired
    @Qualifier("surveyService")
    private SurveyService surveyService;
    
    @Autowired
    @Qualifier("answerValidator")
    private AnswerValidator answerValidator;
    
    
    // ------------------------------------------------------------------------|
    // --- CONSTRUCTORS -------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- CLASS METHODS ------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- INSTANCE METHODS ---------------------------------------------------|
    // ------------------------------------------------------------------------|

    /**
     * Setup binder for adding/editing answers.
     */
    @InitBinder
    protected void initBinder(PortletRequestDataBinder binder) {
        
        // required to bind skip-to-question
        binder.registerCustomEditor(Question.class, new QuestionPropertyEditor(getQuestionService()));
        binder.registerCustomEditor(AnswerMode.class, new AnswerModePropertyEditor());
    }

    // ------------------------------------------------------------------------|

    @ModelAttribute("answer")
    public Answer getCommandObject(@RequestParam("answerID") Long answerId) {
        
        return getAnswerService().findById(answerId);
    }

    // ------------------------------------------------------------------------|
    
    /**
     * Edits an answer (Edit, render phase.)
     * 
     * @param questionId 
     * @param answerId 
     * @param model 
     * @return The attribute in the model defining the action of editing an answer.
     */
    @RenderMapping(params="action=showEditAnswerForm")
    public String showEditAnswerForm(@RequestParam("questionID") Long questionId, 
            @RequestParam("answerID") Long answerId, Model model) {
        
        Answer answer = getAnswerService().findById(answerId);
    	Question question = getQuestionService().findById(questionId);
    	Survey survey = question.getSurvey();
    	
        if (question.getAnswersType().compareTo(AnswersType.SINGLE_ANSWER) == 0) {
            // the only valid mode for SINGLE_ANSWER questions is USER_DESC
            List<AnswerMode> purgedModes = new ArrayList<AnswerMode> ();
            purgedModes.add(AnswerMode.CUSTOM_DESC);
            model.addAttribute("answerModeValues", purgedModes);
        }
        else {
            model.addAttribute("answerModeValues", Arrays.asList(AnswerMode.values()));
        }

        model.addAttribute("question", question);
        model.addAttribute("answerPositions", getQuestionService().findValidAnswerPositions(question, answer));
        
        // It makes no sense for an answer of a AnswersType.MULTIPLE_CHOICE question
        // to have a skip-to-question. The use case is: if you choose this answer then
        // you're redirected to this question.
        if (question.getAnswersType() == AnswersType.SINGLE_CHOICE || question.getAnswersType() == AnswersType.SINGLE_ANSWER) {
            model.addAttribute("skipToQuestions", getSurveyService().findValidSkipToQuestions(survey, answer));
        }
        
        return "answerEdit";
    }

    // ------------------------------------------------------------------------|

    /**
     * Saves an existing answer after validating it (Edit, action phase.)
     * 
     * @param request 
     * @param response 
     * @param answer 
     * @param result 
     * @param sessionStatus 
     */
    @ActionMapping(params="action=editAnswer")
    public void submitEditAnswerForm(ActionRequest request, ActionResponse response,
            @ModelAttribute("answer") Answer answer, BindingResult result, SessionStatus sessionStatus) {

        getAnswerValidator().validate(answer, result);
        
        if (!result.hasErrors()) {
            Answer savedAnswer = getAnswerService().save(answer);
            response.setRenderParameter("action", "viewQuestionAnswers");
            response.setRenderParameter("questionID", savedAnswer.getQuestion().getId().toString());
        }
        else {
            if (logger.isDebugEnabled()) {
                for (ObjectError error: result.getAllErrors()) {
                    logger.debug("Answer edit form reported [" + error.toString() + "]");
                }
            }
            
            response.setRenderParameter("action", "showEditAnswerForm");
            response.setRenderParameter("answerID", answer.getId().toString());
            response.setRenderParameter("questionID", answer.getQuestion().getId().toString());
        }
    }

    // --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --|
    // ---[  GETTERS AND SETTERS  ]--------------------------------------------|
    // --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --|

    /**
     * @return the answerValidator
     */
    public AnswerValidator getAnswerValidator() {
        
        return answerValidator;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param answerValidator the answerValidator to set
     */
    public void setAnswerValidator(AnswerValidator answerValidator) {
        
        this.answerValidator = answerValidator;
    }

    // ------------------------------------------------------------------------|

    /**
     * @return the answerService
     */
    public AnswerService getAnswerService() {
        
        return answerService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param answerService the answerService to set
     */
    public void setAnswerService(AnswerService answerService) {
        
        this.answerService = answerService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @return the questionService
     */
    public QuestionService getQuestionService() {
        
        return questionService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param questionService the questionService to set
     */
    public void setQuestionService(QuestionService questionService) {
        
        this.questionService = questionService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @return the surveyService
     */
    public SurveyService getSurveyService() {
        return surveyService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param surveyService the surveyService to set
     */
    public void setSurveyService(SurveyService surveyService) {
        this.surveyService = surveyService;
    }

    // ------------------------------------------------------------------------|

}
